# Create your views here.
from django.shortcuts import render_to_response
from jeux.models import Game
from jeux.models import Word
from django.http import (HttpResponseForbidden, HttpResponseBadRequest,
                         HttpResponseRedirect)
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import never_cache
from annoying.decorators import ajax_request, render_to
from django.http import (HttpResponseForbidden, HttpResponseBadRequest,
                         HttpResponseRedirect)
from django.views.decorators.http import require_POST, require_GET
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User

def game_required(func):
    def f(request, id, *args, **kw):
        game = get_object_or_404(Game, pk=id)
        if request.user not in game.players.all():
            return HttpResponseForbidden()
        request.game = game
        return func(request, *args, **kw)
    return login_required(f)

@login_required
@render_to('active_games.html')
def index(request):
    return active_games_dict(request.user)
    
@game_required
@require_GET
@render_to('index.html')
def get_game(request):
    this=request.game.players.filter(username=request.user.username).all()
    thisplayer=this[0]
    return { 'game': request.game, 'thisplayer': thisplayer, 'ismyturn': (request.user == request.game.current_player)}

@require_GET
@ajax_request
def word_in_dictionary(request):
    word = request.GET['word']
    dictionary = get_dictionary('anglais')
    return {
        'word': word,
        'in_dictionary': word in dictionary,
    }


def get_dictionary(dict_name):
    
    # TODO make this setup.py aware
    if hasattr(get_dictionary, dict_name):
        return getattr(get_dictionary, dict_name)

    import os.path
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                        'data', '%s.txt' % dict_name)

    with file(path, 'r') as fp:
        d = set(line.strip() for line in fp)

    setattr(get_dictionary, dict_name, d)
    return d
    

@never_cache
@login_required
@require_GET
@ajax_request
def active_games_json(request):
    return dict((k, [immutable_state(game, request.user) for game in games])
                    for k, games in active_games_dict(request.user).iteritems())

def active_games_dict(user):
    active_qs = user.game_set
    inactive_qs = user.game_set
    return {
        'all':active_qs.all(),
        'my_turn': active_qs.filter(current_player=user),
        'other': active_qs.exclude(current_player=user),
    }

@game_required
@require_GET
@ajax_request
def game_immutable_state(request):
    return immutable_state(request.game, request.user)

@game_required
@require_GET
@ajax_request
def isMyturn(request):
    if request.user != request.game.current_player:
        return {'ismyturn':False}
    return {'ismyturn':True}

def immutable_state(game, user):
    player_num = game.gameplayer_set.get(user=user).player_num
    return {
        'players': [{
                'username': u.username,
                'first_name': u.first_name,
                'last_name': u.last_name
            } for u in game.get_players()],
        'player_num': player_num,
        'url': game.get_absolute_url()
    }

@game_required
@require_GET
@ajax_request
def game_finish(request):
    playerfiltered=request.game.gameplayer_set.filter(user=request.game.current_player)
    other=request.game.players.all()
    otherplayer=request.game.gameplayer_set.get(user=other[0])
    thisplayer=request.game.gameplayer_set.get(user=other[1])
    if thisplayer.score>otherplayer.score:
        thisplayer.winner=True
        thisplayer.save();
        request.game.save()
        return {'thisplayer':thisplayer.user.username,'score':thisplayer.score}
    else:
        otherplayer.winner=True
        otherplayer.save();
        request.game.save()
        return {'otherplayer':otherplayer.user.username,'otherscore':otherplayer.score}

@game_required
@require_GET
@ajax_request
def game_skip(request):
    if request.user != request.game.current_player:
        return HttpResponseForbidden('<h1>c est pas ton tour</h1>')
    playerfiltered=request.game.gameplayer_set.filter(user=request.game.current_player)
    thisplayer=playerfiltered[0]
    thisplayer.save()
    other=request.game.players.exclude(username=request.user.username).all()
    otherplayer=request.game.gameplayer_set.get(user=other[0])
    request.game.current_player=other[0]
    request.game.save()
    return { 'request.user': request.user.username, 
            'request.game.current_player' : request.game.current_player.username}

@game_required
@require_GET
@ajax_request
def game_play(request):
    if request.user != request.game.current_player:
        return HttpResponseForbidden('<h1>c est pas ton tour</h1>')
    request.game.tile = request.GET['tile']
    word = Word(word=request.GET['word'])
    word.score=len(word.word)*100
    word.save()
    playerfiltered=request.game.gameplayer_set.filter(user=request.game.current_player)
    thisplayer=playerfiltered[0]
    thisplayer.score+=word.score
    thisplayer.words.add(word)
    thisplayer.save()
    other=request.game.players.exclude(username=request.user.username).all()
    otherplayer=request.game.gameplayer_set.get(user=other[0])
    if request.game.tile.find('.')==-1:
        if thisplayer.score>otherplayer.score:
            thisplayer.winner=True
            thisplayer.save();
            request.game.save()
            return {'winner':thisplayer.user.username}
        else:
            otherplayer.winner=True
            otherplayer.save();
            request.game.save()
            return {'winner':request.game.gameplayer_set.get(user=request.game.current_player).user.username}
    request.game.current_player=other[0]
    request.game.save()
    return { 'request.user': request.user.username, 
            'request.game.current_player' : request.game.gameplayer_set.get(user=request.game.current_player).user.username, 
            'words':[{
                'word': w.word
            } for w in thisplayer.get_words()]}
